# 🤖 Full Agent + Streamlit + LangChain

Complete Streamlit application with LangChain agent, multiple tools, RAG (FAISS), and enterprise-grade security.

[![Python 3.11+](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/)
[![LangChain](https://img.shields.io/badge/LangChain-1.1.2-green.svg)](https://python.langchain.com/)
[![Streamlit](https://img.shields.io/badge/Streamlit-1.51+-red.svg)](https://streamlit.io/)

---

## 📋 Table of Contents

1. [Overview](#overview)
2. [Features](#features)
3. [Prerequisites](#prerequisites)
4. [Installation](#installation)
5. [Execution](#execution)
6. [Project Structure](#project-structure)
7. [Security & Quality](#security--quality)
8. [Troubleshooting](#troubleshooting)

---

## 🎯 Overview

Production-ready AI assistant combining:
- ✅ **Streamlit** - Modern web interface with tabs
- ✅ **LangChain Agents** - Intelligent orchestration with tool calling
- ✅ **LangGraph** - State management and checkpointing
- ✅ **Ollama** - Local LLMs (qwen2.5, llama3.1, etc.)
- ✅ **RAG with FAISS** - Knowledge base search
- ✅ **Two-Layer Safety** - Moderation + Guardrails

---

## ✨ Features

| Feature | Description |
|---------|-------------|
| 🤖 **Multi-Model Support** | Switch between Ollama models on-the-fly |
| 📊 **Context Visualization** | Real-time token usage monitoring |
| 🔍 **RAG Search** | FAISS vector database with PDF support |
| 🛡️ **Security Layer** | PII redaction, injection blocking, DLP |
| ✅ **Quality Layer** | Citation check, tone validation |
| 🧪 **RAG Evaluation** | Built-in evaluation with Judge LLM |
| 📈 **Visualization Tab** | Decision path and execution traces |

---

## 📦 Prerequisites

### Essential:
- **Ollama** installed and running
- **qwen2.5** or **llama3.1** model (supports tool calling)

### For Docker:
- **Docker Desktop** installed
- 4GB RAM available

### For local installation:
- **Python 3.11 or 3.12**
- **Poetry** (recommended) or **pip**

---

## 🚀 Installation

We have organized the installation process by Operating System to make it easier for you.

### Option 1: Docker (Recommended) 🐳

Docker ensures an **isolated environment** and **full compatibility**.

1.  **Install Docker Desktop**
    *   [Windows/Mac/Linux Download](https://www.docker.com/products/docker-desktop)
2.  **Start Ollama** (System-level)
    *   Make sure `ollama serve` is running on your host machine.
    *   Pull the model: `ollama pull qwen2.5` or `ollama pull llama3.1`
3.  **Run with Docker**
    ```bash
    docker-compose up --build -d
    ```

4.  **Access:** http://localhost:8505

---

### Option 2: Windows (Native) 💻

We provide automated scripts to handle dependencies.

#### 1. System Setup
Run the `install.ps1` script to install system dependencies (C++ Redistributable, Ollama, Graphviz):
```powershell
.\setup\windows\install.ps1
```

#### 2. Python Setup
```powershell
# Create virtual environment (recommended)
python -m venv .venv
.\.venv\Scripts\activate

# Install libraries
pip install -r requirements.txt
```

#### 3. (Optional) GPU Acceleration
If you have an NVIDIA GPU, fix PyTorch to use CUDA:
```batch
.\setup\windows\fix_pytorch_cuda.bat
```

#### 4. Run Locally
```powershell
streamlit run ui.py
```

---

### Option 3: macOS (Native) 🍎

#### 1. System Setup
Use the script to install dependencies via Homebrew (Graphviz, Ollama):
```bash
chmod +x setup/mac/install.sh
./setup/mac/install.sh
```

#### 2. Python Setup
```bash
# Create virtual environment (recommended)
python3 -m venv .venv
source .venv/bin/activate

# Install libraries
pip install -r requirements.txt
```

#### 3. Run Locally
```bash
streamlit run ui.py
```

---

### Option 4: Poetry (Alternative)

```bash
# 1. Install Poetry
curl -sSL https://install.python-poetry.org | python3 -

# 2. Install dependencies
poetry install

# 3. Run
poetry run streamlit run ui.py
```

---

## 🎮 Execution

### Quick Start

```bash
# 1. Ensure Ollama is running
ollama serve

# 2. Run application
streamlit run ui.py
# OR with Poetry
poetry run streamlit run ui.py
# OR with Docker
docker-compose up -d

# 3. Access
open http://localhost:8501  # Local
open http://localhost:8505  # Docker
```

### Setup Tab Features

- **Model Selection**: Switch between installed Ollama models
- **Temperature**: Adjust creativity (0.0-1.0)
- **Context Window**: Configure input token limit
- **Max Output**: Set response length limit

---

## 📁 Project Structure

```
Full Agent + streamlit + langchain/
├── setup/                     # 📂 INSTALLATION SCRIPTS
│   ├── windows/               # Windows specific setup
│   └── mac/                   # macOS specific setup
├── ui.py                      # Main Streamlit entry point
├── tabs/                      # UI Tabs (modular)
│   ├── chat_tab.py            # Chat interface
│   ├── setup_tab.py           # Model configuration
│   ├── rag_tab.py             # Knowledge Base manager
│   ├── visualization_tab.py   # Execution traces
│   ├── quality_validation_tab.py  # RAG Evaluation
│   └── help_tab.py            # Documentation
├── src/                       # Source code
│   ├── llm/                   # Agent factory, Ollama client
│   ├── rag/                   # RAG implementation, FAISS
│   ├── moderation/            # Security layer (PII, DLP)
│   ├── guardrails/            # Quality validators
│   ├── tools/                 # Agent tools
│   └── utils/                 # Utilities, callbacks
├── config/                    # Configuration files
│   └── model_config.yaml      # Main config
├── data/                      # Data directory
│   ├── docs/books/            # PDF documents
│   └── embeddings/            # FAISS index
├── Dockerfile                 # Docker configuration
├── docker-compose.yml         # Docker orchestration
├── pyproject.toml             # Poetry dependencies
└── requirements.txt           # pip dependencies
```

---

## 🛡️ Security & Quality

### Two-Layer Safety System

#### 1. Moderation Layer ("The Police")
- **Location**: `src/moderation/manager.py`
- **Checks**: Toxicity, Injection, PII Masking, DLP
- **Action**: Blocks unsafe content

#### 2. Guardrails ("Quality Assurance")
- **Location**: `src/guardrails/validators.py`
- **Checks**: Citations, Tone, Completeness
- **Action**: Warns on quality issues

### RAG Evaluation Metrics

| Metric | Description | Threshold |
|--------|-------------|-----------|
| **Groundedness** | Answer supported by context | ≥ 0.7 |
| **Relevance** | Answer addresses question | ≥ 0.6 |
| **Completeness** | All aspects covered | ≥ 0.6 |

---

## 🔧 Troubleshooting

### Ollama Connection

```bash
# Check if running
curl http://localhost:11434/api/tags

# Start if needed
ollama serve
```

### Docker Issues

```bash
# View logs
docker-compose logs -f

# Restart
docker-compose restart

# Clean rebuild
docker-compose down -v
docker-compose up --build
```

### FAISS Index Not Found

```bash
# Add PDFs to data/docs/books/
# Then regenerate index
python src/rag/generate_vector_db.py
```

---

## 📚 Resources

- [LangChain Docs](https://python.langchain.com/)
- [Streamlit Docs](https://docs.streamlit.io/)
- [Ollama Docs](https://ollama.ai/docs)
- [FAISS](https://github.com/facebookresearch/faiss)

---

## 👨‍💻 Author

**CTW Team** - GenAI Workshop

---

**Ready for the Workshop! 🚀**
